###  float模型直接放到板端
import numpy as np
import pathlib

# 获取父路径
parent_path = pathlib.Path(__file__).parent.absolute()
# 拼接路径
out_path = parent_path / "../../Arm_STM32_FreedomLearn/freedomlearn"
# 解析路径（处理相对路径符号 `..`）
out_path = out_path.resolve()

# 加载模型参数
def load_model_parameters(file_path):
    data = np.load(file_path)
    w_i_h = data['w_i_h']
    w_h_o = data['w_h_o']
    b_i_h = data['b_i_h']
    b_h_o = data['b_h_o']
    print(f"模型参数已从 {file_path} 加载")
    return w_i_h, w_h_o, b_i_h, b_h_o

# 将模型参数写入单个 C 文件
def save_model_parameters_to_c(file_path, w_i_h, w_h_o, b_i_h, b_h_o):
    with open(file_path, "w") as f:
        # 写入 w_i_h
        f.write("float w_i_h[] = {\n")
        for i, value in enumerate(w_i_h.flatten()):
            f.write(f"{value}f, ")
            if (i + 1) % 10 == 0:  # 每行显示 10 个值
                f.write("\n")
        f.write("\n};\n\n")

        # 写入 w_h_o
        f.write("float w_h_o[] = {\n")
        for i, value in enumerate(w_h_o.flatten()):
            f.write(f"{value}f, ")
            if (i + 1) % 10 == 0:  # 每行显示 10 个值
                f.write("\n")
        f.write("\n};\n\n")

        # 写入 b_i_h
        f.write("float b_i_h[] = {\n")
        for i, value in enumerate(b_i_h.flatten()):
            f.write(f"{value}f, ")
            if (i + 1) % 10 == 0:  # 每行显示 10 个值
                f.write("\n")
        f.write("\n};\n\n")

        # 写入 b_h_o
        f.write("float b_h_o[] = {\n")
        for i, value in enumerate(b_h_o.flatten()):
            f.write(f"{value}f, ")
            if (i + 1) % 10 == 0:  # 每行显示 10 个值
                f.write("\n")
        f.write("\n};\n")

    print(f"模型参数已保存到 {file_path}")

# 加载模型参数
w_i_h, w_h_o, b_i_h, b_h_o = load_model_parameters("./NeuralNetworkFromScratch-main/result/model_parameters.npz")

# 将模型参数写入单个 C 文件
save_model_parameters_to_c(f"{out_path}/model_parameters.c", w_i_h, w_h_o, b_i_h, b_h_o)